package com.sap.sap_mangers.controller;

import com.sap.sap_mangers.pojo.SapActivity;
import com.sap.sap_mangers.service.ActivityService;
import com.sap.sap_mangers.service.CacheService;
import com.sap.sap_mangers.service.DynamicService;
import com.sap.sap_mangers.service.UserService;
import com.sap.sap_mangers.until.JwtUtil;
import com.sap.sap_mangers.until.SimpleJson;
import com.sap.sap_mangers.until.SnowflakeIdWorker;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.List;
import java.util.Objects;

/**
 * @author 樊东升
 * @date 2022/8/13 23:10
 */
@RestController
@RequestMapping("/Activity")
public class ActivityController {

    private final DynamicService dynamicService;
    private final ActivityService activityService;
    private final CacheService cacheService;
    private final UserService userService;

    @Autowired
    public ActivityController(DynamicService dynamicService, ActivityService activityService, CacheService cacheService, UserService userService) {
        this.dynamicService = dynamicService;
        this.activityService = activityService;
        this.cacheService = cacheService;
        this.userService = userService;
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    static
    class HttpRequestParameter {
        private String context;
        private String topic;
        private String note;
        private String fileUrl;
        private List<MultipartFile> files;
        private String year;
        private String order;
    }

    public HttpRequestParameter initHttpRequest(HttpServletRequest httpRequest) {
        MultipartHttpServletRequest params = ((MultipartHttpServletRequest) httpRequest);
        return new HttpRequestParameter(params.getParameter("context"),
                params.getParameter("topic"),
                params.getParameter("note"),
                params.getParameter("fileUrl"),
                ((MultipartHttpServletRequest) httpRequest).getFiles("images"),
                params.getParameter("year"),
                params.getParameter("order"));
    }

    @PreAuthorize("hasAuthority('会长')")
    @PostMapping("/addActivity")
    public SimpleJson addActivity(HttpServletRequest httpRequest) {
        HttpRequestParameter httpRequestParameter = initHttpRequest(httpRequest);
        if (httpRequestParameter.getContext().isEmpty() || httpRequestParameter.getTopic().isEmpty() || httpRequestParameter.getNote().isEmpty()) {
            return new SimpleJson(3, "除了附件地址可为空，其余内容皆不可为空！");
        }
        SapActivity sapActivity = new SapActivity();
        sapActivity.setActivityYear(Long.parseLong(dynamicService.getYear()));
        sapActivity.setActivityOrder(activityService.getActivity(Integer.valueOf(dynamicService.getYear())) + 1);
        sapActivity.setActivityUsername(JwtUtil.getUserForToken());
        sapActivity.setActivityCreateTime(new Timestamp(System.currentTimeMillis()));
        setSapActivity(
                httpRequestParameter.getFiles(),
                httpRequestParameter.getContext(),
                httpRequestParameter.getTopic(),
                httpRequestParameter.getNote(),
                httpRequestParameter.getFileUrl(),
                sapActivity);
        String realNameCache = "姓名获取失败";
        List<SapActivity> activityForYear = activityService.getActivityForYear(Integer.valueOf(dynamicService.getYear()));
        if (!activityForYear.isEmpty()) {
            if (Objects.equals(activityForYear.get(0).getActivityUsername(), JwtUtil.getUserForToken())) {
                if (userService.getUserByUserName(JwtUtil.getUserForToken()).getRole() != 1) {
                    return new SimpleJson(2, "上一次也是由学号:" + JwtUtil.getUserForToken() + "(" + realNameCache + ")完成活动总结，我们不允许同一个人连续两次完成活动总结，请更换其他人完成活动总结");
                }
            }
        }
        return activityService.addActivity(sapActivity, httpRequestParameter.getFiles());
    }

    /**
     * 设置SapActivity类的一些内容，通过set注入
     *
     * @param files       图片组
     * @param context     活动内容
     * @param topic       活动标题
     * @param note        活动备注
     * @param fileUrl     活动附件地址
     * @param sapActivity 活动表
     */
    private void setSapActivity(List<MultipartFile> files, String context, String topic, String note, String fileUrl, SapActivity sapActivity) {
        String realNameCache = cacheService.getRealNameCache(cacheService.getRealNameCacheMap(), JwtUtil.getUserForToken());
        sapActivity.setActivityName(realNameCache);
        sapActivity.setActivityReviseName(realNameCache);
        sapActivity.setActivityTopic(topic);
        sapActivity.setActivityNote(note);
        sapActivity.setActivityContext(context);
        sapActivity.setActivityImageNum(files.size());
        SnowflakeIdWorker snowflakeIdWorker = new SnowflakeIdWorker(0, 0);
        sapActivity.setActivityImageId(snowflakeIdWorker.nextId());
        sapActivity.setActivityImageFileUrl(fileUrl);
    }

    @PreAuthorize("hasAuthority('会长')")
    @PostMapping("/updateActivity")
    public SimpleJson updateActivity(HttpServletRequest httpRequest) {
        HttpRequestParameter httpRequestParameter = initHttpRequest(httpRequest);
        int year = Integer.parseInt(httpRequestParameter.getYear());
        int order = Integer.parseInt(httpRequestParameter.getOrder());
        if (httpRequestParameter.getContext().isEmpty() || httpRequestParameter.getTopic().isEmpty() || httpRequestParameter.getNote().isEmpty()) {
            return new SimpleJson(3, "除了附件地址可为空，其余内容皆不可为空！");
        }
        SapActivity sapActivity = new SapActivity();
        sapActivity.setActivityYear(year);
        sapActivity.setActivityOrder(order);
        sapActivity.setActivityReviseUsername(JwtUtil.getUserForToken());
        sapActivity.setActivityReviseTime(new Timestamp(System.currentTimeMillis()));
        setSapActivity(
                httpRequestParameter.getFiles(),
                httpRequestParameter.getContext(),
                httpRequestParameter.getTopic(),
                httpRequestParameter.getNote(),
                httpRequestParameter.getFileUrl(),
                sapActivity);
        return activityService.updateActivity(sapActivity, httpRequestParameter.getFiles());
    }

    @PreAuthorize("hasAuthority('游客')")
    @GetMapping("/getActivityForYear")
    public SimpleJson getActivityForYear(@RequestParam("year") Integer year) {
        List<SapActivity> activityForYear = activityService.getActivityForYear(year);
        return new SimpleJson(0, "获取成功", activityForYear);
    }

    @PreAuthorize("hasAuthority('游客')")
    @GetMapping("/getActivityAll")
    public SimpleJson getActivityAll() {
        List<SapActivity> activityAll = activityService.getActivityAll();
        return new SimpleJson(0, "获取成功", activityAll);
    }

    @PreAuthorize("hasAuthority('游客')")
    @GetMapping("/getActivityForOrder")
    public SimpleJson getActivityForOrder(@RequestParam("year") Integer year, @RequestParam("order") Integer order) {
        if (year == null || order == null) {
            return new SimpleJson(1, "请完整上传参数");
        }
        SapActivity activityForOrder = activityService.getActivityForOrder(year, order);
        return new SimpleJson(0, activityForOrder);
    }

    /**
     * 获取最近的一次活动
     *
     * @return 一条活动内容记录
     */
    @PreAuthorize("hasAuthority('游客')")
    @GetMapping("/getCurrentActivity")
    public SimpleJson getCurrentActivity() {
        return new SimpleJson(0, "成功", activityService.getCurrentActivity());
    }
}
